//
//  UIButton+NEDWebImage.m
//  NEDCategory
//
//  Created by 98du on 2021/11/29.
//

#import "UIButton+NEDWebImage.h"
#import "UIImage+NEDStyle.h"
#import "NEDConstant.h"
#import "NSString+NEDWebImage.h"
#import <SDWebImage/UIButton+WebCache.h>
#import <NEDCategory/UIImage+NED.h>

@implementation UIButton (NEDWebImage)

-(void)ned_setImage:(NSString *)urlString{
    [self ned_setImage:urlString withState:UIControlStateNormal placeholderImage:nil];
}
-(void)ned_setImageOrigin:(NSString *)urlString{
    [self ned_setImage:urlString withState:UIControlStateNormal placeholderImage:[UIImage ned_placeHolder] isOrigin:YES];
}

-(void)ned_setImageHighlight:(NSString *)urlString{
    [self ned_setImage:urlString withState:UIControlStateHighlighted placeholderImage:nil];
}
-(void)ned_setImageSelected:(NSString *)urlString{
    [self ned_setImage:urlString withState:UIControlStateSelected placeholderImage:nil];
}

-(void)ned_setImage:(NSString *)urlString placeholderImage:(nullable UIImage *)placeholderImage{
    [self ned_setImage:urlString withState:UIControlStateNormal placeholderImage:placeholderImage];
}
-(void)ned_setImage:(NSString *)urlString withState:(UIControlState)controlState placeholderImage:(nullable UIImage *)placeholderImage{
    [self ned_setImage:urlString withState:controlState placeholderImage:placeholderImage isOrigin:NO];
}
-(void)ned_setImage:(NSString *)urlString withState:(UIControlState)controlState placeholderImage:(nullable UIImage *)placeholderImage isOrigin:(BOOL)isOrigin{
    if (IsNull(placeholderImage)) {
        placeholderImage = [UIImage ned_placeHolder];
    }
    if(![urlString isKindOfClass:[NSString class]]){
        [self setImage:placeholderImage forState:controlState];
        return;
    }
    WS(weakSelf)
    NSURL * url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]];
    if (url && [url pathComponents].count > 1) {
        NSString * imageURL = urlString.ned_OSSURLPath;
        if(!isOrigin){
            imageURL = [imageURL ned_OSSReszeFit];
        }
        if (placeholderImage) {
            [self sd_setImageWithURL:[NSURL URLWithString:[imageURL stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]] forState:controlState placeholderImage:placeholderImage];
        }else{
            [self sd_setImageWithURL:[NSURL URLWithString:[imageURL stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]] forState:controlState];
        }
    }else if (IsNull(urlString)) {
        [self setImage:placeholderImage forState:controlState];
    } else{
        UIImage * image = [UIImage imageNamed:urlString];
        if (IsNull(image)) {
            image = placeholderImage;
        }
        [self setImage:image forState:controlState];
    }

}

@end
